package sqlSession;

import config.BoundSql;
import pojo.Configuration;
import pojo.MappedStatement;
import utils.GenericTokenParser;
import utils.ParameterMapping;
import utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //获取连接
        Connection connection = configuration.getDataSource().getConnection();

        //获取sql 并处理成带？的
        String sql = mappedStatement.getSql();
        BoundSql boundSql = BoundSql(sql);

        //获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getParse());

        //获取传入参数的类型
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        //设置参数
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);

            String content = parameterMapping.getContent();

            //反射
            Field declaredField = parameterClass.getDeclaredField(content);
            declaredField.setAccessible(true);

            //获取参数值
            Object o = declaredField.get(params[0]);

            //给占位符赋值
            preparedStatement.setObject(i+1,o);
        }

        ResultSet resultSet = preparedStatement.executeQuery();

        Class<?> resultTypeClass = getClassType(mappedStatement.getResultType());
        ArrayList<Object> list = new ArrayList<>();

        while (resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();

            for (int i = 0; i < metaData.getColumnCount(); i++) {
                //属性名称
                String catalogName = metaData.getColumnName(i+1);
                //属性值
                Object object = resultSet.getObject(catalogName);

                //创建属性描述器，为属性⽣成读写⽅法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(catalogName, resultTypeClass);
                //获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                //向类中写入值
                writeMethod.invoke(o,object);
            }
            list.add(o);
        }
        return (List<E>) list;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        Connection connection = configuration.getDataSource().getConnection();

        String sql = mappedStatement.getSql();

        BoundSql boundSql = BoundSql(sql);

        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getParse());

        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClasss = getClassType(parameterType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        for (int i = 0; i < parameterMappings.size(); i++) {

            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();

            Field declaredField = parameterClasss.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1,o);
        }
        //执行sql
        preparedStatement.execute();
//        System.out.println(preparedStatement.getResultSet());
        //获取到的影响行数
        return preparedStatement.getUpdateCount();
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType!=null){
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }

    private BoundSql BoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);

        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }

}
